package com.xiaotao.consumer;

import com.rabbitmq.client.Channel;
import com.xiaotao.entity.UserCoupon;
import com.xiaotao.mapper.UserCouponMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class UserCouponConsumer {
    @Resource
    private UserCouponMapper userCouponMapper;

    @RabbitListener(queues = {"userCouponQueue"})
    public void consume(Integer msg, Channel channel, Message message) {
        try {
            UserCoupon userCoupon = userCouponMapper.queryById(msg);
            if (userCoupon.getStatus() == 1) {
                userCouponMapper.updateStatus(userCoupon);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
